<template>
  <div class="layout">
    <div class="header">
      <div class="headContent">
        <div class="title">
          <img :src="logoImg" />
          <span>{{ t('sys.login.sysTitle') }}</span></div
        >
        <div class="time">{{ time }}{{ weekDay }}</div>
      </div>
    </div>
    <div class="cardCr">
      <div class="card">
        <div class="title"
          ><span>{{ t('sys.login.studentInfoRegister') }}</span>
        </div>

        <a-card>
          <a-form ref="formRef" :model="form" :rules="registerRules" :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }">
            <FormNav :navTitle="$t('sys.login.studentBasicInfo')" />
            <a-form-item :label="$t('sys.login.school')" name="school">
              <a-select v-model:value="form.schoolId" :placeholder="$t('sys.login.selectPlaceholder')" @change="handleChange">
                <a-select-option  v-for="item in schoolOptions" :key="item.value" :value="item.value">{{item.label}}</a-select-option>
                
              </a-select>
            </a-form-item>

          
            <a-form-item :label="$t('sys.login.department')" name="department">
              <a-select v-model:value="form.departmentId" :placeholder="$t('sys.login.selectPlaceholder')" @change="departChange">
                <a-select-option  v-for="item in departOptions" :key="item.value" :value="item.value">{{item.label}}</a-select-option>
                
              </a-select>
            </a-form-item>
              <a-form-item :label="$t('sys.login.major')" name="major">
              <a-select v-model:value="form.majorId" :placeholder="$t('sys.login.selectPlaceholder')" @change="majorChange">
                <a-select-option  v-for="item in majorOptions" :key="item.value" :value="item.value">{{item.label}}</a-select-option>
                
              </a-select>
            </a-form-item>


         
        
           <a-form-item :label="$t('sys.login.name')" name="name">
              <a-input v-model:value="form.name" :placeholder="$t('sys.login.namePlaceholder')" />
            </a-form-item>

            <a-form-item :label="$t('sys.login.studentId')" name="studentId">
              <a-input v-model:value="form.studentId" :placeholder="$t('sys.login.studentIdPlaceholder')" />
            </a-form-item>

           
            <FormNav :navTitle="$t('sys.login.accountSettingInfo')" />

          <!--   <a-form-item :label="$t('sys.login.mobile')" name="mobile">
              <a-input v-model:value="form.mobile" :placeholder="$t('sys.login.mobilePlaceholder')" />
            </a-form-item> -->

            <!--    <a-form-item :label="$t('sys.login.smsCode')" name="smsCode">
              <a-input-group compact>
                <a-input v-model:value="form.smsCode" style="width: 180px" :placeholder="$t('sys.login.smsPlaceholder')" />
                <a-button type="primary" @click="getPhoneCode" style="width: 90px" :disabled="!showInterval">{{
                  showInterval ? '获取验证码' : `${timeRuning}s后重试`
                }}</a-button>
              </a-input-group>
            </a-form-item> -->

            <a-form-item :label="$t('sys.login.setPassword')" name="password">
              <a-input-password v-model:value="form.password" placeholder="请输入密码" />
            </a-form-item>

            <a-form-item :label="$t('sys.login.inputCode')" name="inputCode">
              <div class="iptCode">
                <a-input class="fix-auto-fill" type="text" :placeholder="t('sys.login.inputCode')" v-model:value="form.inputCode" />

                <div class="code">
                  <img v-if="randCodeData.requestCodeSuccess" :src="randCodeData.randCodeImage" @click="handleChangeCheckCode" />
                  <img v-else style="margin-top: 2px; max-width: initial" :src="codeImg" @click="handleChangeCheckCode" />
                </div>
              </div>
            </a-form-item>
            <a-form-item name="policy" :wrapper-col="{ span: 12, offset: 3 }">
              <div class="aui-flex">
                <div class="aui-flex-box">
                  <div class="aui-choice">
                    <a-checkbox v-model:checked="form.policy" />
                    <span style="margin-left: 5px">{{ t('sys.login.policyText') }}</span>
                    <span style="color: #1b90ff; margin-left: 4px" @click="goPolicy">{{ t('sys.login.policy') }}</span>
                  </div>
                </div>
              </div>
            </a-form-item>

            <a-form-item :wrapper-col="{ span: 12, offset: 3 }">
              <a-button type="primary" class="registerButton" html-type="submit" @click="registerHandleClick">{{
                t('sys.login.submitRegister')
              }}</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </div>

      <div class="copyright"> copyright@2024-2025版权所属西安智慧社区技术科技有限公司</div>
      <!-- 图片验证码弹窗 -->
    </div>
    <CaptchaModal @register="captchaRegisterModal" @ok="getLoginCode" />
  </div>
</template>

<script lang="ts" setup name="mini-register">
  import {  register } from '/@/api/sys/user';
  import { defineComponent,ref, toRaw,reactive, onMounted, unref, computed } from 'vue';
  import { getWeekDay, formatTime } from '@/utils/time';
  import type { FormInstance } from 'ant-design-vue';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { SmsEnum } from '/@/views/sys/login/useLogin';
  import logoImg from '@/assets/images/logo.png';
  import { Form, Input, Select, Button, Card, Layout, InputPassword, InputGroup } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {queryParentIdTree} from '@/api/common/api';
  import FormNav from '@/components/formNav/src/FormNav.vue';
  import CaptchaModal from '@/components/jeecg/captcha/CaptchaModal.vue';
  import codeImg from '/@/assets/images/checkcode.png';
  import { validatePasswordStrength, validateMobileNumber, validateAgree, validateStudentId } from '@/utils/validate';
  import { ExceptionEnum } from '@/enums/exceptionEnum';
  import { getCaptcha, getCodeInfo } from '/@/api/sys/user';
import { on } from 'events';
  const { notification, createMessage } = useMessage();
  const emit = defineEmits(['go-back', 'success', 'register']);
  const { Option: SelectOption } = Select;
  const { Content: LayoutContent } = Layout;
  const timeRuning = ref<number>(60);
  const [captchaRegisterModal, { openModal: openCaptchaModal }] = useModal();
  const randCodeData = reactive<any>({
    randCodeImage: '',
    requestCodeSuccess: false,
    checkKey: null,
  });
  const schoolOptions = ref([])
  const formRef = ref<FormInstance | null>(null);
  const { t } = useI18n();
  const time = computed(() => formatTime());
  const weekDay = computed(() => getWeekDay());
  const majorOptions = ref([])
  
  //是否显示获取验证码
  const showInterval = ref<boolean>(true);

  const form = reactive({
    schoolId: '',
    departmentId: '',
    majorId: '',
    classId: '',
    studentId: '',
    name: '',
    //mobile: '',
    // smsCode: '',
    password: '',
    inputCode: '',
    policy: false,
  });
  //定时器
  const timer = ref<any>(null);
  const departOptions = ref([])
  //注册表单规则项
  const registerRules = reactive({
    school: [
      {
        required: true,
        message: '请选择院校',
        trigger: 'blur',
      },
    ],
    class: [
      {
        required: true,
        message: '请选择班级',
        trigger: 'blur',
      },
    ],
    department: [
      {
        required: true,
        message: '请选择院系',
        trigger: 'blur',
      },
    ],
    major: [
      {
        required: true,
        message: '请选择专业',
        trigger: 'blur',
      },
    ],
    /*   smsCode: [
      {
        required: true,
        message: '请输入手机验证码',
        trigger: 'blur',
      },
    ], */

    studentId: [
      { required: true, message: '请填写学号', trigger: 'blur' },
      { validator: validateStudentId, trigger: 'change' },
    ],

    /*  
      checkPass: [{ validator: validatePass2, trigger: 'change' }],
      age: [{ validator: checkAge, trigger: 'change' }],
      phoneCode: [{ validator: checkAge, trigger: 'change' }], */
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { validator: validatePasswordStrength, trigger: 'change' },
    ],
    inputCode: [{ required: true, message: '请填写图形验证码' }],
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { type: 'string', pattern: /^[a-zA-Z\u4e00-\u9fa5\s]+$/, message: '姓名不能包含特殊字符' },
    ],
    mobile: [{ required: true, validator: validateMobileNumber, trigger: 'change' }],
    policy: [{ required: true, validator: validateAgree, trigger: 'blur' }],
  });

  /**
   * 获取验证码
   */
  function handleChangeCheckCode() {
    form.inputCode = '';
    //update-begin---author:chenrui ---date:2025/1/7  for：[QQYUN-10775]验证码可以复用 #7674------------
    randCodeData.checkKey = new Date().getTime() + Math.random().toString(36).slice(-4); // 1629428467008;
    //update-end---author:chenrui ---date:2025/1/7  for：[QQYUN-10775]验证码可以复用 #7674------------
    getCodeInfo(randCodeData.checkKey).then((res) => {
      randCodeData.randCodeImage = res;
      randCodeData.requestCodeSuccess = true;
    });
  }
  /**
   * 获取手机验证码
   */
  async function getPhoneCode() {
    if (!form.mobile) {
      createMessage.warn(t('sys.login.mobilePlaceholder'));
      return;
    }

    //update-begin---author:wangshuai---date:2024-04-18---for:【QQYUN-9005】同一个IP，1分钟超过5次短信，则提示需要验证码---
    const result = await getCaptcha({ mobile: form.mobile, smsmode: SmsEnum.REGISTER }).catch((res) => {
      if (res.code === ExceptionEnum.PHONE_SMS_FAIL_CODE) {
        openCaptchaModal(true, {});
      }
    });
    //update-end---author:wangshuai---date:2024-04-18---for:【QQYUN-9005】同一个IP，1分钟超过5次短信，则提示需要验证码---
    if (result) {
      const TIME_COUNT = 60;
      if (!unref(timer)) {
        timeRuning.value = TIME_COUNT;
        showInterval.value = false;
        timer.value = setInterval(() => {
          if (unref(timeRuning) > 0 && unref(timeRuning) <= TIME_COUNT) {
            timeRuning.value = timeRuning.value - 1;
          } else {
            showInterval.value = true;
            clearInterval(unref(timer));
            timer.value = null;
          }
        }, 1000);
      }
    }
  }
  //处理选择变更
  const handleChange =async (value)=>{
    console.log(value)
    try {
    const res =   await queryParentIdTree(value)
    console.log(res)
     departOptions.value =  res.map((item)=>({label:item.title,value:item.id}))

      
    } catch (error) {
      console.log(error)
      
    }
  }
  const getAllSchool = async()=>{
    try {
    const res =   await  queryParentIdTree()
    console.log('allScholl',res)
   schoolOptions.value=  res.map((item)=>({
      label:item.title,
      value:item.id
    }))
      
    } catch (error) {
      console.log(error)
      
    }
  }

  //注册
  const registerHandleClick = () => {
    if (!formRef.value) {
      console.error('formRef 未初始化');
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        console.log('表单验证通过:', form);
        registerAccount();
      })
      .catch((error) => {
        console.error('表单验证失败:', error);
      });
  };
  async function registerAccount() {
    try {
      const resultInfo = await register(
        toRaw({
          name: form.name,
          password: form.password,
          mobile: form.mobile,
          schoolId: form.schoolId,
          departmentId: form.departmentId,
          majorId: form.majorId,
          classId: form.classId,
          studentId: form.studentId,
          inputCode: form.inputCode,
          policy: form.policy,
        })
      );
      if (resultInfo && resultInfo.data.success) {
        notification.success({
          message: t('sys.api.registerMsg'),
          description: resultInfo.data.message || t('sys.api.registerMsg'),
          duration: 3,
        });
        emit('success', { username: form.name, password: form.password });
        initForm();
      } else {
        notification.warning({
          message: t('sys.api.errorTip'),
          description: resultInfo.data.message || t('sys.api.networkExceptionMsg'),
          duration: 3,
        });
      }
    } catch (error) {
      notification.error({
        message: t('sys.api.errorTip'),
        description: error.message || t('sys.api.networkExceptionMsg'),
        duration: 3,
      });
    }
  }
    function initForm() {
    Object.assign(form,{name:'',mobile: '',  password: '', 
          schoolId: '',
          departmentId: '',
          majorId:'',
          classId:'',
          studentId: '',
          inputCode: '',
         policy: false})
   /*  if(!unref(timer)){
      showInterval.value = true;
      clearInterval(unref(timer));
      timer.value = null;
    } */
   if (formRef.value) {
  formRef.value.resetFields();
} else {
  console.warn('formRef is null');
}
   
  }
 const departChange =async (value)=>{
   console.log(value)
    try {
    const res =   await queryParentIdTree(value)
    console.log(res)
     majorOptions.value =  res.map((item)=>({label:item.title,value:item.id}))

      
    } catch (error) {
      console.log(error)
      
    }


 } 
 

  onMounted(async() => {
   handleChangeCheckCode();
   await getAllSchool()
 
  });

</script>

<style scoped lang="less">
  @import '/@/assets/loginmini/style/home.less';

  .layout {
    min-height: 100vh;
    width: 100vw;
    background: rgb(135, 235, 177);

    .header {
      width: 100%;
      height: 40px;
      background: #ffffff;
    }
    .headContent {
      width: 50%;
      height: 100%;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title {
        font-size: 22px;
        font-weight: 600;
        height: 100%;
        display: flex;
      }
    }
    .cardCr {
      display: flex;
      flex-direction: column;
      align-items: center;
      height: calc(100vh - 40px);
    }
    .card {
      width: 50%;
      border: 1px solid skyblue;
      margin: 15px auto;
      height: 92%;
      // display: flex;
      // flex-direction: column;
      // align-items: center;
      background: #ffffff;

      .title {
        background: #1890ff;
        width: 100%;
        height: 50px;
        display: flex;
        font-size: 20px;
        justify-content: center;
        align-items: center;
        color: white;
      }
      .ant-card {
        height: calc(100% - 50px);
        // width: 60%;
        margin-left: 25%;
        overflow-y: auto;
        .ant-card-body {
          .ant-form {
            .iptCode {
              display: flex;
              align-items: center;
              .code img {
                margin-left: 6px;
              }
            }
            .registerButton {
              width: 100%;
            }
          }
        }
      }
      .ant-card-bordered {
        border: none;
      }
    }
    .copyright {
      height: 8%;
      color: #ffffff;
      font-size: 14px;
      // position: fixed;
      // bottom: 15px;
      // left: 45%;
    }
  }
</style>
